<template>
  <div>
    <!-- 头部导航 -->
    <headers title="账号登录"></headers>
    <div class="login">
      <!-- 账号密码 -->
      <van-form @submit="onSubmit" class="form">
        <!-- 账号 -->
        <van-field
          class="form-item"
          v-model="username"
          name="username"
          placeholder="请输入账号"
        />
        <!-- 密码 -->
        <van-field
          class="form-item"
          v-model="password"
          type="password"
          name="password"
          placeholder="请输入密码"
        />
        <!-- 登录按钮 -->
        <div>
          <van-button class="btn" block type="info" native-type="submit">
            登 录
          </van-button>
        </div>
      </van-form>
      <!-- 注册 -->
      <div class="registe">
        <span @click="$router.push('/registe')">还没有账号，去注册~</span>
      </div>
    </div>
  </div>
</template>

<script>
import Headers from '@/components/Headers.vue'
import { userLoginAPI } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  components: {
    Headers
  },
  data() {
    return {
      username: '',
      password: '',
      usernameRules: /^[A-Za-z0-9]{5,8}$/,
      passwordRules: /^[A-Za-z0-9]{5,12}$/
    }
  },
  methods: {
    ...mapMutations(['SET_TOKEN']),
    async onSubmit() {
      const { username, password, usernameRules, passwordRules } = this
      // 判断用户名密码
      if (!username.trim() || !password.trim()) {
        return this.$toast('用户名和密码不能为空')
      }
      if (!usernameRules.test(username)) {
        return this.$toast('用户名格式5-8位的字母和数字')
      }
      if (!passwordRules.test(password)) {
        return this.$toast('密码格式5-12位的字母和数字')
      }
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      // 发送登录请求
      const data = await userLoginAPI(username, password)
      if (data.status === 400) {
        return this.$toast(data.description)
      }
      // 存储登录令牌
      this.SET_TOKEN(data.body)
      this.$router.push('/home/profile')
      this.$toast.success({
        message: '登录成功',
        icon: 'passed'
      })
    }
  }
}
</script>

<style scoped lang="less">
.login {
  margin: 0 15px;
}
.form {
  margin-top: 21px;
  // 输入框
  .form-item {
    height: 62px;
    margin-bottom: 9px;
    padding: 2px 0;
    font-size: 17px;
    line-height: 60px;
    border-bottom: 1px solid #eee;
    background-color: transparent;
  }
  // 按钮
  .btn {
    height: 50px;
    margin-top: 24px;
    background-color: #1cb676;
    font-size: 18px;
    border: 1px solid #1cb676;
  }
}
// 注册
.registe {
  margin-top: 30px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  color: #666;
}
</style>
